package com.now.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;


/**
 * @Desc 加密工具
 * @Author TMC
 * @Date 2024/7/23 16:17
 * @Version 1.0
 */
public class AesUtil {
    // 加密字符串 需为16个字符
    private static final String KEY="tianmaochang1234";

    /**
     * 加密
     * @param value
     * @return
     */
    public static String encrypt(String value){
        try {
            Cipher cipher= Cipher.getInstance("AES");
            SecretKeySpec secretKeyspec = new SecretKeySpec(KEY.getBytes(),"AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeyspec);
            byte[]encrypted = cipher.doFinal(value.getBytes());
            return Base64.getEncoder().encodeToString(encrypted);
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解密
     * @param value
     * @return
     */
    public static String decrypt(String value){
        try {
            Cipher cipher = Cipher.getInstance("AES");
            SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(value));
            return new String(decrypted);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}